package com.bwie.service.Impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.bwie.utils.JwtsUtils;
import com.bwie.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.Menu;
import com.bwie.mapper.MenuMapper;
import com.bwie.service.MenuService;
import javax.servlet.http.HttpServletRequest;


@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService{


    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public R selectMenuListById() {
        // 1、通过 token 传递的 id 获取 menu 信息
        String token = request.getHeader("token");
        Integer userId = JwtsUtils.getIdByToken(token);
        List<Menu> menus = menuMapper.selectMenuListById(userId);
        // 2、构建菜单树
        List<Tree<Integer>> path = TreeUtil.build(menus, 0, (menu, TreeNode) -> {
            TreeNode.setId(menu.getId().intValue());
            TreeNode.setName(menu.getName());
            TreeNode.setParentId(menu.getPid());
            TreeNode.putExtra("path", menu.getPath());
        });
        // 3、返回前端
        return R.OK(path);
    }
}
